package gptma.bo.util;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public final class GptmaUtils {

	private GptmaUtils() {
		// utility methods, do not instanciate
	}

	public static Date[] getEnclosingMonth(Date date) {
		Date[] ret = new Date[2];

		Calendar cal = Calendar.getInstance(Locale.FRANCE);
		cal.setTime(date);
		cal.set(Calendar.DATE, 1);
		resetTimeInfo(cal);

		// 1st day of month, 00h00
		ret[0] = cal.getTime();

		// 1st day of next month 00h00
		cal.add(Calendar.MONTH, 1);
		ret[1] = cal.getTime();

		return ret;
	}

	public static Date[] getEnclosingMonth(int month, int year) {
		Calendar cal = Calendar.getInstance(Locale.FRANCE);
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);

		return getEnclosingMonth(cal.getTime());
	}

	public static Date[] getEnclosingWeek(Date date) {
		Date[] ret = new Date[2];

		Calendar cal = Calendar.getInstance(Locale.FRANCE);
		cal.setTime(date);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		resetTimeInfo(cal);

		ret[0] = cal.getTime();

		cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
		cal.set(Calendar.HOUR_OF_DAY, 24);
		ret[1] = cal.getTime();

		return ret;
	}

	/**
	 * Clears time information. This is used so that caching works as passed
	 * parameters are always the same (whereas different when time info is set:
	 * new Date() for example)
	 * 
	 * @param date
	 * @return
	 */
	public static Date resetTimeInfo(Date date) {
		Calendar cal = Calendar.getInstance(Locale.FRANCE);
		cal.setTime(date);
		resetTimeInfo(cal);

		return cal.getTime();
	}

	public static void resetTimeInfo(Calendar calendar) {
		calendar.clear(Calendar.HOUR_OF_DAY);
		calendar.clear(Calendar.MINUTE);
		calendar.clear(Calendar.SECOND);
		calendar.clear(Calendar.MILLISECOND);
	}
}
